import { PayloadAction, createSlice } from '@reduxjs/toolkit'
import { IUser } from '../../models/types'

export const usersSlice = createSlice({
	name: 'users', // 命名空间，在调用action的时候会默认的设置为action的前缀
	// 初始值
	initialState: {
		users: [{ id: '001', name: 'tom', age: 18 }]
	},
	// 这里的属性会自动的导出为actions，在组件中可以直接通过dispatch进行触发
	reducers: {
		addUser: (preState, action: PayloadAction<IUser>) => {
			const { users } = preState
			const { payload} = action
			return {
				users: [payload, ...users]
			}
		}
	}
})

// 导出actions
export const { addUser: addUserActon } = usersSlice.actions

 // 内置了thunk插件，可以直接处理异步请求
export const asyncIncrement = (payload: IUser) => (dispatch: (arg0: { payload: IUser; type: string }) => void) => {
	setTimeout(() => {
		dispatch(addUserActon(payload))
	}, 2000)
}

export default usersSlice.reducer